/*
*Copyright 2021-2023 NERCIS
*
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/

package cn.ac.nercis.pes.community.controller.manage;

import cn.ac.nercis.pes.community.component.dialog.MessageType;
import cn.ac.nercis.pes.community.controller.base.GlobalEventHandle;
import cn.ac.nercis.pes.community.controller.base.InitDataLoad;
import cn.ac.nercis.pes.community.manager.RealTimeSaveManager;
import cn.ac.nercis.pes.community.mapper.manage.EvaluationUnitViewMapper;
import cn.ac.nercis.pes.community.model.vo.manage.EvaluationUnitVO;
import cn.ac.nercis.pes.community.support.FXMLController;
import cn.ac.nercis.pes.community.utils.*;
import cn.ac.nercis.pes.model.dto.manage.EvaluationUnitDTO;
import cn.ac.nercis.pes.service.manage.EvaluationUnitService;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.StackPane;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.net.URL;
import java.util.ResourceBundle;
import java.util.concurrent.CompletableFuture;

/**
 * 测评单位管理控制器
 * @author zpy
 * @version 1.0.0
 */
@Slf4j
@FXMLController
public class EvaluationUnitController implements Initializable, GlobalEventHandle, InitDataLoad {
    @FXML
    private StackPane page;
    @FXML
    private Button saveButton;
    @FXML
    private TextField nameText;
    @FXML
    private TextField addressText;
    @FXML
    private TextField shortNameText;
    @FXML
    private TextField postalCodeText;
    @FXML
    private TextField contactPersonText;
    @FXML
    private TextField contactPositionText;
    @FXML
    private TextField contactDepartmentText;
    @FXML
    private TextField contactTelText;
    @FXML
    private TextField contactPhoneText;
    @FXML
    private TextField contactEmailText;

    private final EvaluationUnitVO unitVO = new EvaluationUnitVO();
    private final EvaluationUnitService evaluationUnitService;
    private final RealTimeSaveManager realTimeSaveManager = new RealTimeSaveManager(this::realTimeSave);

    @Autowired
    public EvaluationUnitController(EvaluationUnitService evaluationUnitService) {
        this.evaluationUnitService = evaluationUnitService;
    }


    @Override
    public void initialize(URL location, ResourceBundle resources) {
        saveButton.setGraphic(IconUtils.getGlyph("save-button-icon","btn-icon"));
        this.bindProperty();
        GuiStore.applyQuickSave(this.page,this::onGlobalSave);
        realTimeSaveManager.listenerTextChange(contactPersonText,contactPositionText,contactDepartmentText,
                contactTelText,contactPhoneText,contactEmailText);
    }

    @Override
    public void initializeData() {
        this.loadData();
    }

    @Override
    public void onGlobalSave() {
        LogUtils.info(log, "执行快捷保存操作...");
        saveEvaluation(false);
    }

    @FXML
    public void onSave(){
        LogUtils.info(log, "执行保存操作...");
        saveEvaluation(false);
    }

    public void realTimeSave(){
        LogUtils.info(log, "执行即时保存操作...");
        saveEvaluation(true);
    }

    private void bindProperty(){
        //控件绑定到数据模型
        this.nameText.textProperty().bindBidirectional(unitVO.nameProperty());
        this.shortNameText.textProperty().bindBidirectional(unitVO.shortNameProperty());
        this.addressText.textProperty().bindBidirectional(unitVO.addressProperty());
        this.postalCodeText.textProperty().bindBidirectional(unitVO.postalCodeProperty());
        this.contactPersonText.textProperty().bindBidirectional(unitVO.contactPersonProperty());
        this.contactPositionText.textProperty().bindBidirectional(unitVO.contactPositionProperty());
        this.contactDepartmentText.textProperty().bindBidirectional(unitVO.contactDepartmentProperty());
        this.contactTelText.textProperty().bindBidirectional(unitVO.contactTelProperty());
        this.contactPhoneText.textProperty().bindBidirectional(unitVO.contactPhoneProperty());
        this.contactEmailText.textProperty().bindBidirectional(unitVO.contactEmailProperty());
    }

    private void loadData() {
        CompletableFuture.supplyAsync(this.evaluationUnitService::findEvaluationUnit)
                .thenAccept(res -> Platform.runLater(() -> {
                    unitVO.setId(res.getId());
                    unitVO.setName(res.getName());
                    unitVO.setShortName(res.getShortName());
                    unitVO.setAddress(res.getAddress());
                    unitVO.setPostalCode(res.getPostalCode());
                    unitVO.setContactPerson(res.getContactPerson());
                    unitVO.setContactPosition(res.getContactPosition());
                    unitVO.setContactDepartment(res.getContactDepartment());
                    unitVO.setContactTel(res.getContactTel());
                    unitVO.setContactPhone(res.getContactPhone());
                    unitVO.setContactEmail(res.getContactEmail());
                }));
    }

    private void saveEvaluation(boolean isRealTime) {
        EvaluationUnitDTO unitDTO = EvaluationUnitViewMapper.INSTANCE.toDTO(unitVO);
        CompletableFuture.supplyAsync(() -> this.evaluationUnitService.save(unitDTO))
                .thenAccept(res-> Platform.runLater(()->{
                    if(isRealTime){
                        if(!res.isSuccess()){
                            log.error("即时保存失败：{}",res.getMsg());
                            LogUtils.record(log,"保存数据：{}",unitDTO);
                        }
                    }else{
                        if(res.isSuccess()){
                            AppUtils.showMessageDialog("保存成功", MessageType.SUCCESS,page);
                        }else if(!res.isSuccess()){
                            AppUtils.showMessageDialog(res.getMsg(),MessageType.FAIL,page);
                        }
                    }
                }));
    }
}